package com.koo.modules.comm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koo.common.exception.RRException;
import com.koo.common.response.R;
import com.koo.common.utils.MyDateUtil;
import com.koo.common.utils.SynDataUtil;
import com.koo.common.utils.UserUtils;
import com.koo.framework.config.DBConfig;
import com.koo.modules.base.util.ServiceUtil;
import com.koo.modules.comm.entity.CommUploadRecordEntity;
import com.koo.modules.comm.service.CommUploadRecordService;
import com.koo.modules.comm.service.SynDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Description：
 * @Author: charlin
 * @Date: 2023/1/3 15:51
 */
@Service
public class SynDataServiceImpl implements SynDataService {

    @Autowired
    private CommUploadRecordService uploadRecordService;


    @Override
    public Integer getDownloadCount(String tableName, Long storeId) {
        List<CommUploadRecordEntity> records = uploadRecordService.listByTableName(storeId, tableName);
        return SynDataUtil.getDownloadCount(tableName, storeId.toString(), records);
    }

    @Override
    public R downloadProductFromCenter(String tableName, Long storeId) {
        String clickColumn = "clickProductDownload";
        String downloadStatusKey = storeId.toString().concat(":product");
        Integer resultCount = 0;
        if (!ServiceUtil.isDataMigrated()) {
            throw new RRException("请先进行数据迁移, 数据迁移过后才可进行数据下载功能");
        }
        if (ServiceUtil.getCacheStatus(downloadStatusKey) || ServiceUtil.getIntProperty(clickColumn) > 0) {
            throw new RRException("您已经点击下载商品数据, 请耐心等待");
        }
        try {
            ServiceUtil.updateDBConfigClickStatus(clickColumn, 1, downloadStatusKey);
            Integer count = getDownloadCount(tableName, storeId);
            if (count > ServiceUtil.MAX_ONE_DOWNLOAD_COUNT) {
                for (int i = 0; i < count; i += ServiceUtil.MAX_ONE_DOWNLOAD_COUNT) {
                    resultCount += this.downloadProduct(tableName);
                }
            } else {
                resultCount += this.downloadProduct(tableName);
            }
            return resultCount > 0 ? R.ok( "成功更新" + resultCount + "条商品数据!") : R.error( "暂无商品数据更新...");
        } finally {
            ServiceUtil.updateDBConfigClickStatus(clickColumn, 0, downloadStatusKey);
        }
    }


    @Override
    @Transactional
    public Integer downloadProduct(String tableName) {
        Date modifyDate = MyDateUtil.getCurrDateTime();
        Long storeId = UserUtils.getStoreId();
        List<CommUploadRecordEntity> records = uploadRecordService.listByTableName(storeId, tableName);
        JSONObject jsonObject = SynDataUtil.downloadProductData(storeId, records);
        JSONArray datas = jsonObject.getJSONArray("data");
        Integer rowsCount = 0;//记录本次商品数据更新了多少
        JSONArray columns = datas.getJSONArray(datas.size() - 1);
        JSONArray codes = datas.getJSONArray(datas.size() - 2);
        String codeColumn = codes.getString(0);
        List<Map<String, Object>> insertColumn = new ArrayList<>();
        String oldRemark = "";
        String tablePK = DBConfig.getTablePKByTableName(tableName);
        if (datas.size() > 3) {
            oldRemark = datas.getJSONArray(0).getString(89);
        }
//        for (int i = 0, end = datas.size() - 2; i < end; i++) {
//            Map<String, Object> inData = new HashMap<>();
//            JSONArray columnData = datas.getJSONArray(i);// 获取每一行数据
//            for (int j = 0, dataSize = columnData.size(), columnSize = columns.size(); j < dataSize && j < columnSize; j++) {
//                inData.put(columns.getString(j), columnData.get(j));
//            }
//            String remark = inData.get("remark").toString();
//            this.modifyProductData(inData);
//            if (StringUtil.isNotEmpty(oldRemark) && !oldRemark.equals(remark)) {
//                JSONArray prevColumn = datas.getJSONArray(i - 1);
//                Date maxDownloadDate = prevColumn.getDate(46);
//                String maxDownloadId = prevColumn.getString(0);
//                updateDownloadDate(tableName, maxDownloadDate, storeId, maxDownloadId, oldRemark);
//                oldRemark = remark;
//            }
//            if (i == end - 1) {
//                Date maxDownloadDate = columnData.getDate(46);
//                String maxDownloadId = columnData.getString(0);
//                updateDownloadDate(tableName, maxDownloadDate, storeId, maxDownloadId, remark);
//            }
//            inData.put("modifyDate", modifyDate);
//            String code = codes.getString(i + 1);
//            String dataSource = inData.get("dataSource").toString();
//            List<Map<String, Object>> tablePks = sysUploadDataRecordDAO.findProductByCode(codeColumn, code, tableName, tablePK, storeId, dataSource);
//            if (tablePks.size() > 0) {
//                remove(inData, tablePK);
//                inData.put("tradeOldPrice", tablePks.get(0).get("tradePrice"));
//                rowsCount += sysUploadDataRecordDAO.updateDataByTableName(inData, tablePK, tablePks, tableName);
//            } else {
//                inData.put("createDate", modifyDate);
//                inData.put("productId", StringUtil.generate16ShortUUID());
//                inData.put("storeId", storeId);
//                //创建或者关联供应商
//                inData.put("storeCode_d", currentUser.getStoreCode());//用后即删
//                initSupplier(inData, remark);
//                insertColumn.add(inData);
//            }
//        }
//        if(insertColumn.size() > 0) {
//            sysUploadDataRecordDAO.insertSupplier_Product(insertColumn);
//        }
//        rowsCount += dataInsert(insertColumn, tableName);
        return rowsCount;
    }




    private void modifyProductData(Map<String, Object> inData) {
        inData.put("totalStorage", 0);//总库存
        inData.put("averagePrice", Double.parseDouble(inData.get("tradePrice").toString()));//平均成本价
        inData.put("localRetailPrice", Double.parseDouble(inData.get("retailPrice").toString()));//本地零售价
        inData.put("memberPrice", Double.parseDouble(inData.get("retailPrice").toString()));//会员价
        inData.put("sellingPrice1", 0);//售价1
        inData.put("sellingPrice2", 0);//售价2
        inData.put("localBarCode", "");//本地条码
        inData.put("propertyName", "");//属性名称
        inData.put("brandId", "");//品牌id
        inData.put("priceFloat", 0);//价格浮动
        inData.put("goodsAllocation", "");//货位
        inData.put("afterScatteredUnit", "");//拆零后单位
        inData.put("scatteredCoefficient", "");//拆零系数
        inData.put("status", 0);//状态 0禁用 1正常
        inData.put("isAudit", 1);//审核标志 0禁用 1正常
        inData.put("isCancel", 0);//作废标志 0否 1是
//        inData.put("createUserId", null == user ? null : user.getUserId());//制单人id
//        inData.put("createUserName", null == user ? null : user.getUserName());//制单人姓名
//        inData.put("storageUpper", 0);//库存上限
//        inData.put("storageFloor", 0);//库存下限
//        inData.put("remark", inData.get("remark").toString().concat("_ZDXZ"));//备注
//        inData.put("auditDate1", null);//审核时间1
//        inData.put("auditDate2", null);//审核时间2
//        inData.put("deleteFlag", 0);//删除标志 -1删除 0正常
//        inData.put("isWebSale", 0);//是否网销
//
//        if (MyStrUtil.isNotEmpty(inData.get("unit")) && StockConstant.SPLIT_UNIT_KG.equalsIgnoreCase(inData.get("unit").toString())) {
//            inData.put("unit", StockConstant.SPLIT_UNIT_G);
//            inData.put("tradePrice", new BigDecimal(inData.get("tradePrice").toString()).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_DOWN));
//            inData.put("retailPrice", new BigDecimal(inData.get("retailPrice").toString()).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_DOWN));
//            inData.put("memberPrice", new BigDecimal(inData.get("memberPrice").toString()).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_DOWN));
//        }
    }
}
